package com.cpic.blood.core.utils;

import com.alibaba.fastjson.JSONArray;
import com.cpic.blood.core.thread.BloodCallable;
import com.cpic.blood.core.thread.ThreadPoolUtils;
import com.cpic.blood.core.vo.HiveFileConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.FutureTask;

@Slf4j
public class HiveFileUtils {

    public static void runHiveFileTask(String inputPath) throws Exception {
        List<String> filesAndDirectories = DirectoryUtils.getFilesAndDirectories(inputPath);
        if (filesAndDirectories == null || filesAndDirectories.size() == 0) {
            log.info("文件目录为空");
            return;
        }

        // 打印所有文件和目录路径
        List<HiveFileConfigVo> hiveFileConfigVoList = new ArrayList<>();
        ThreadPoolUtils newInstance = ThreadPoolUtils.getNewInstance();
//        CountDownLatch cdl = new CountDownLatch(filesAndDirectories.size());
        for (String path : filesAndDirectories) {
            BloodCallable callable = new BloodCallable(path);
            FutureTask<HiveFileConfigVo> futureTask = new FutureTask<HiveFileConfigVo>(callable);
            newInstance.executor(new Thread(futureTask));
            HiveFileConfigVo vo = futureTask.get();
            hiveFileConfigVoList.add(vo);
        }
        String json = JSONArray.toJSONString(hiveFileConfigVoList);
        JSONArray jsonArray = JSONArray.parseArray(json);
        String filePath = ConfigUtil.HIVE_OUT_DIR + "hive_output_" + DateUtil.getSimpleDateTime() + ".txt";
        try {
            //线程阻塞直到计数器为0
//            cdl.await();
            FileUtils.writeLines(new File(filePath), jsonArray);
            newInstance.showDown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copyHiveFileTask() throws IOException {
        ThreadPoolUtils newInstance = ThreadPoolUtils.getNewInstance();
        String inputFile = "D:\\code\\000029\\job_1682490134365_29947_conf.xml";
        for (int i = 30000; i < 40000; i++) {
            String outputFile = "D:\\code\\000029\\job_1682490134365_" + i + "_conf.xml";
            //newInstance.executor(new ThreadTask(inputFile, outputFile));
        }
        log.info("生成文件完成...");
        newInstance.showDown();
    }

    public static void main(String[] args) {
        try {
            long startTime = System.currentTimeMillis();
            runHiveFileTask(ConfigUtil.HIVE_INPUT_DIR);
            long endTime = System.currentTimeMillis();
            log.info("执行完毕时间为：" + (endTime - startTime) / 1000 + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
//        try {
//            copyHiveFileTask();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

}
